package com.hello.rabbitlistener;

import com.Constants;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class Producer {
    @Autowired//RabbitTemplate
    private AmqpTemplate template;

    //注入进来仅仅只是为了获取队列名，可以不用注入此对象
    @Autowired
    private Queue queue;

    public void send(String msg){
        System.out.println("send:Thread.currentThread().getName() = " + Thread.currentThread().getName());

        //template.convertAndSend(Constants.QUEUE_NAME, msg);
        template.convertAndSend(queue.getName(), msg);

        System.out.println("发送了消息：" +msg);
    }


    public void sendMessage(){
        System.out.println("send:Thread.currentThread().getName() = " + Thread.currentThread().getName());
        String content = "send msg...";

        Message msg = new Message(content.getBytes(StandardCharsets.UTF_8));
        msg.getMessageProperties()
                .getHeaders()
                .put("h1", "h1 value");
        msg.getMessageProperties().setContentType("text/plain");

        template.convertAndSend(queue.getName(), msg);

        System.out.println("发送了消息(Message)：" +msg);
    }

    public void rpc(){
        System.out.println("send:Thread.currentThread().getName() = " + Thread.currentThread().getName());
        String content = "rpc";
        Message msg = new Message(content.getBytes(StandardCharsets.UTF_8));

        //convertSendAndReceive是阻塞方法，只有收到返回值之后才继续运行
        Object receive = template.convertSendAndReceive(queue.getName(), msg);

        System.out.println("发送了消息(Message)：" +msg);
        System.out.println("接收到了：receive = " + receive);
    }
}
